package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.minio.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.pojos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        List<ApArticle> articleList = apArticleMapper.load(dto, 1);
        return ResponseResult.okResult(articleList);
    }

    @Override
    public ResponseResult load2(ArticleHomeDto dto) {
        if (dto==null){
            log.warn("入参不能为空");
            return ResponseResult.okResult("");
        }
        String tag = dto.getTag();
        //查缓存
        String s = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + tag);
        if (StringUtils.isEmpty(s)){
            return load(dto);
        }
        List<ApArticle> apArticles = JSON.parseArray(s, ApArticle.class);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dto) {
        List<ApArticle> articleList = apArticleMapper.load(dto, 1);
        return ResponseResult.okResult(articleList);
    }

    @Override
    public ResponseResult loadnew(ArticleHomeDto dto) {
        List<ApArticle> articleList = apArticleMapper.load(dto, 2);
        return ResponseResult.okResult(articleList);
    }

    @Override
    @Async
    public void generate(Long articleId) {
        // 1. 获取文章详情
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent articleContent = apArticleContentMapper.selectOne(wrapper);
        if (articleContent == null) {
            log.error("文章不存在");
            return;
        }
        // 2. 将content字段提取出来
        Map<String, Object> map = new HashMap<>();
        map.put("content", JSON.parseArray(articleContent.getContent()));
        // 3. 调用freemarker插件,生成html文件
        InputStream is = freemarkerGenerator.generate("article.ftl", map);
        // 4. 调用minIO插件,实现文件上传
        String url = minIoTemplate.uploadFile("", articleId + ".html", is, "html");
        // 5. 更新表中字段
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);

        String content = articleContent.getContent();
        createArticleESIndex(apArticle, content);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {

        // dto 判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        Long id = dto.getId();
        String content = dto.getContent();

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        if (id == null) {
            // 新增article表
            int insertResult = apArticleMapper.insert(apArticle);
            if (insertResult < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            // 新增article_config表
            ApArticleConfig config = new ApArticleConfig();
            config.setIsDown(false);
            config.setIsDelete(false);
            config.setIsForward(true);
            config.setIsComment(true);
            config.setArticleId(apArticle.getId());

            int insertConfigResult = apArticleConfigMapper.insert(config);
            if (insertConfigResult < 1) {
                log.warn("文章配置添加失败");
                throw new RuntimeException("文章配置添加失败");
            }
            // 新增article_content表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(content);
            apArticleContent.setArticleId(apArticle.getId());
            int insertContentResult = apArticleContentMapper.insert(apArticleContent);
            if (insertContentResult < 1) {
                log.warn("文章内容添加失败");
                throw new RuntimeException("文章内容添加失败");
            }

            generate(apArticle.getId());

            return ResponseResult.okResult(apArticle.getId());

        } else {
            // 修改
            int articleUpdateResult = apArticleMapper.updateById(apArticle);
            if (articleUpdateResult < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }

            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId, id);

            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(content);

            int contentUpdateResult = apArticleContentMapper.update(apArticleContent, wrapper);
            if (contentUpdateResult < 1) {
                throw new RuntimeException("内容表修改失败");
            }
        }
        generate(id);
        return ResponseResult.okResult(id);
    }

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //入参校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //登录校验
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        boolean isLike = false, isUnLike = false, isCollection = false, isFollow = false;
        Long articleId = dto.getArticleId();
        Integer authorId = dto.getAuthorId();
        //点赞
        Object o = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId, userId.toString());
        if (o!=null){
         isLike=true;
        }
        //不喜欢
        Object o1 = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId.toString(), userId.toString());
        if (o1!=null){
            isUnLike=true;
        }
        //收藏
        Object o2 = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + articleId.toString(), userId.toString());
        if (o2!=null){
            isCollection=true;
        }
        //关注
        Object o3 = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + userId.toString(),authorId.toString());
        if (o3!=null){
            isFollow=true;
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isLike);
        resultMap.put("islike", isUnLike);
        resultMap.put("isunlike", isCollection);
        resultMap.put("iscollection", isFollow);

        return ResponseResult.okResult(resultMap);
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 送消息，创建索引
     *
     * @param apArticle
     * @param content
     */
    private void createArticleESIndex(ApArticle apArticle, String content) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, vo);
        vo.setContent(content);

        kafkaTemplate.send("article.update.index.topic", JSON.toJSONString(vo));
    }
}
